package com.xuetang9.fujian.socketdemo.udpdemo.onetoone;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/9 14:54
 * @version: V1.0
 * @package: com.xuetang9.fujian.socketdemo.udpdemo.onetoone
 **/
public class UDPServer {
    // 自定义的服务器端口最好使用1000以后的端口
    private final static int port = 9527;

    public static void main(String[] args) throws IOException {
        // 服务器端会首先接收来自客户端发来的信息
        // 1.创建服务端要接收的数据报对象
        byte[] packetBuffer = new byte[2048];
        DatagramPacket packet = new DatagramPacket(packetBuffer,packetBuffer.length);
        // 2.启动服务端，监听某个端口
        DatagramSocket server = new DatagramSocket(port);
        System.out.println("udp服务端已开启，正在监听端口：" + port + "，等待客户端的连接");
        server.receive(packet);
        String message = new String(packetBuffer,0,packet.getLength());
        System.out.println("成功接收到来自客户端的消息：" + message);
        message = "你好啊，客户端";

        InetAddress clientAddress = InetAddress.getByName("localhost");
        packet = new DatagramPacket(message.getBytes(),message.getBytes().length,clientAddress,9257);
        server.send(packet);
        new Scanner(System.in).next();
    }

}
